import React, {useEffect, useState} from 'react';
import { Form, Button, DatePicker,TreeSelect,Upload,Input, Modal,Row,message, Col,Select} from 'antd';
import { connect } from 'umi';
import moment from 'moment';
import {UploadOutlined} from '@ant-design/icons';
import {getUploadUrl} from '@/utils/upload';
import {vacationType} from "@/utils/constant";
import {getResidueDay,getRealLeaveDay} from '../service';

const FormItem = Form.Item;
const { TextArea } = Input;
const {Option} = Select;
const { RangePicker } = DatePicker;

const formLayout = {
  labelCol: { span: 7 },
};

const colStyle = {
  xl: 8,
  lg: 8,
  md: 8,
  sm: 8,
  xs: 8,
};

let uploadedFiles = [];

const VacationAddForm = (props) => {
  const { onSubmit, onCancel, loading,visible,currentUser,record,title} = props;
  const [form] = Form.useForm();
  const [fileUploadUrls,setFileUploadUrls] = useState([]);
  const [fileName, setFileName] = useState(null);
  const [extra,setExtra] = useState(null);

  // useEffect(() => {
  //   getResidueDay().then(res => {
  //     setExtra("（剩余" + res + "天）");
  //   });
  // }, []);

  const fileList = {
    name: 'file',
    multiple: true,
    action: getUploadUrl(),
    data: {name: fileName},
    defaultFileList: uploadedFiles,
    beforeUpload(file) {
      setFileName(file.name)
    },
    onChange(res) {
      const {status} = res.file;
      if (status === 'done') {
        if (res.file.response.error) {
          message.success(`${res.file.response.error}`);
        } else {
          setFileUploadUrls([...fileUploadUrls,res.file.response ]);
          message.success(`${res.file.name} 文件上传成功`);
        }
      } else if (status === 'error') {
        message.error(`${res.file.name} 文件上传失败`);
      }
    },
    onRemove(info) {
      let urls = fileUploadUrls;
      let index = urls.indexOf(info.url);
      if (index > -1){
        urls.splice(index, 1);
        setFileUploadUrls(urls);
      }
    },
  };

  useEffect(() => {
    if(currentUser){
      if(record && visible){
        form.setFieldsValue({...record,leaveDate:[moment(record.leaveBeginTime),moment(record.leaveEndTime)]});
        setFileUploadUrls(record.fileUrl.split(','));
        if(record.fileUrl){
          let fileList = record.fileUrl.split(',');
          fileList.forEach((item,index) =>{
            uploadedFiles.push({
              uid: index,
              name: item.split('----')[1],
              status: 'done',
              url: item,
            })
          });
        }
      }else{
        form.setFieldsValue({...currentUser,code:currentUser.usercode,unitname:currentUser.department});
      }
    }
  }, [visible]);

  const onFormCancel = () => {
    form.resetFields();
    onCancel();
    uploadedFiles = [];
    setFileUploadUrls([]);
  };

  const handleSubmit = async () => {
    const fieldsValue = await form.validateFields()
    form.resetFields();
    let fileUploadUrlsStr = '';
    fileUploadUrls.forEach(item => {
      if (item){
        if (fileUploadUrlsStr === ''){
          fileUploadUrlsStr += item;
        }else {
          fileUploadUrlsStr += ',' + item;
        }
      }
    });
    onSubmit({
      ...fieldsValue,
      fileUrl:fileUploadUrlsStr,
      leaveBeginTime:moment(fieldsValue.leaveDate[0]).format('YYYY-MM-DD'),
      leaveEndTime:moment(fieldsValue.leaveDate[1]).format('YYYY-MM-DD'),
      id:record && record.id
    });
    uploadedFiles = [];
    setFileUploadUrls([]);
  };

  const computeDay = () =>{
    const fieldsValue = form.getFieldValue();
    let time = fieldsValue.leaveDate[1].diff(fieldsValue.leaveDate[0],'days');
    form.setFieldsValue({leaveDay:time + 1});
    // let value = {
    //   type:fieldsValue.type,
    //   leaveBeginTime:moment(fieldsValue.leaveDate[0]),
    //   leaveEndTime:moment(fieldsValue.leaveDate[1]),
    // };
    // getRealLeaveDay(value).then(res => {
    //   form.setFieldsValue({leaveDay:res});
    // });
  };

  const renderContent = () => {
    return (
      <>
        <Row gutter={24}>
          <Col {...colStyle}>
            <FormItem name="code" label="申请人工号">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="name" label="申请人">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="orgname" label="公司" >
              <TreeSelect disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="unitname" label="部门" >
              <TreeSelect disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="jobname" label="岗位">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="jobLevel" label="职级">
              <Select disabled={true} />
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="type" label="请假类型" rules={[{required: true, message: '请假类型不能为空'}]}>
              <Select placeholder="请选择" allowClear>
                {vacationType.map((item, index) => {
                  return (
                    <Option value={item.value} key={index}>
                      {item.value === 6 && extra ? item.label + extra : item.label}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="leaveDate" label="假期起止日期" rules={[{required: true, message: '假期起止日期不能为空'}]}>
              <RangePicker className='widthStyle' onChange={computeDay}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="leaveDay" label="请假天数" rules={[{required: true, message: '假期起止日期不能为空'}]}>
              <Input disabled={false} suffix="天"/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="urlIds" label="上传附件">
              <Upload {...fileList}>
                <Button>
                  <UploadOutlined/> 点击上传附件
                </Button>
              </Upload>
            </FormItem>
          </Col>
          <Col span={24}>
            <FormItem name="leaveRemark" labelCol={{span: 2}} label="请假说明" rules={[{required: true, message: '请假说明不能为空'}]}>
              <TextArea rows={4} className='widthStyle'/>
            </FormItem>
          </Col>
        </Row>
      </>
    )
  }

  const renderFooter = () => {
    return (
      <>
        <Button onClick={() => onFormCancel()}>取消</Button>
          <Button type="primary" onClick={() => handleSubmit()} loading={loading}>提交</Button>
      </>
    )
  }

  return (
    <Modal
      maskClosable={false}
      width={1280}
      destroyOnClose
      centered
      title={`请假/调休`+title}
      visible={visible}
      footer={renderFooter()}
      onOk={handleSubmit}
      onCancel={() => onFormCancel()}
      onClose={() => onFormCancel()}
      okText="确认"
      cancelText="取消"
    >
      <Form
        {...formLayout}
        form={form}
        style={{ paddingTop: '24px' }}
      >
        {renderContent()}
      </Form>
    </Modal>
  )
}

export default connect(({user}) => ({
  currentUser: user.currentUser,
}))(VacationAddForm)
